<template>
  <div class="square-view">
    <div class="header">
      <h1>美食广场</h1>
      <div class="search-bar">
        <input 
          type="text" 
          placeholder="搜索店铺或美食..." 
          v-model="searchKeyword"
          @keyup.enter="handleSearch"
          :disabled="loading"
        />
        <button @click="handleSearch" :disabled="loading">
          {{ loading ? '搜索中...' : '搜索' }}
        </button>
      </div>
    </div>

    <div class="filters">
      <div 
        v-for="filter in filterOptions" 
        :key="filter"
        class="filter" 
        :class="{ active: activeFilter === filter }"
        @click="handleFilterChange(filter)"
      >
        {{ filter }}
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载店铺数据...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="shops.length === 0" class="empty-container">
      <div class="empty-icon">🏪</div>
      <p>暂无店铺数据</p>
      <button @click="loadShops" class="retry-btn">重新加载</button>
    </div>

    <!-- 店铺列表 -->
    <div v-else class="shop-list">
      <div 
        v-for="shop in shops" 
        :key="shop.id" 
        class="shop-card"
        @click="goToShop(shop.id)"
      >
        <div class="shop-image" :style="{ backgroundImage: `url(${shop.image})` }">
          <div class="promo-tag" v-if="shop.promo">{{ shop.promo }}</div>
        </div>
        <div class="shop-info">
          <h3>{{ shop.name }}</h3>
          <div class="rating">
            <span class="stars">★★★★★</span>
            <span>{{ shop.rating.toFixed(1) }}</span>
            <span>月售{{ shop.monthlySales }}单</span>
          </div>
          <div class="details">
            <span>¥{{ shop.avgPrice }}人均</span>
            <span>配送费¥{{ shop.deliveryFee }}</span>
            <span>{{ shop.deliveryTime }}分钟</span>
          </div>
          <div class="tags">
            <span v-for="(tag, index) in shop.tags" :key="index">{{ tag }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { 
  selectAll as getShops, 
  selectEq as searchShopsEq,
  searchShops,
  type Shop as ApiShop,
  type PageInfo 
} from '@/http/Shop';
import { message } from '@/utils/message';

// 原静态数据接口（保留备用）
// interface Shop {
//   id: number;
//   name: string;
//   image: string;
//   rating: number;
//   avgPrice: number;
//   deliveryFee: number;
//   deliveryTime: number;
//   monthlySales: number;
//   tags: string[];
//   promo?: string;
// }

// 前端展示用的Shop接口（基于后端数据转换）
interface DisplayShop {
  id: number;
  name: string;
  image: string;
  rating: number;
  avgPrice: number;
  deliveryFee: number;
  deliveryTime: number;
  monthlySales: number;
  tags: string[];
  promo?: string;
  description?: string;
  address?: string;
  phone?: string;
  startTime?: string;
  endTime?: string;
}

const router = useRouter();

// 响应式数据
const shops = ref<DisplayShop[]>([]);
const loading = ref(true);
const searchKeyword = ref('');
const activeFilter = ref('全部');
const allShops = ref<DisplayShop[]>([]); // 存储所有店铺数据

// 过滤器选项
const filterOptions = ['全部', '快餐', '饮品', '甜点', '日料', '川菜'];

// 原静态数据（保留备用）
// const staticShops = ref<Shop[]>([
//   {
//     id: 1,
//     name: '香辣小龙虾',
//     image: '/shop001.jpg',
//     rating: 4.8,
//     avgPrice: 45,
//     deliveryFee: 3,
//     deliveryTime: 30,
//     monthlySales: 1240,
//     tags: ['小龙虾', '川味', '夜宵'],
//     promo: '新店优惠'
//   },
//   {
//     id: 2,
//     name: '甜蜜烘焙坊',
//     image: '/shop002.jpg',
//     rating: 4.9,
//     avgPrice: 25,
//     deliveryFee: 0,
//     deliveryTime: 20,
//     monthlySales: 980,
//     tags: ['蛋糕', '面包', '甜点']
//   },
//   {
//     id: 3,
//     name: '和风寿司',
//     image: '/shop003.jpg',
//     rating: 4.7,
//     avgPrice: 65,
//     deliveryFee: 5,
//     deliveryTime: 40,
//     monthlySales: 760,
//     tags: ['寿司', '刺身', '日料'],
//     promo: '满100减20'
//   },
//   {
//     id: 4,
//     name: '元气早餐铺',
//     image: '/shop004.jpg',
//     rating: 4.6,
//     avgPrice: 15,
//     deliveryFee: 2,
//     deliveryTime: 15,
//     monthlySales: 2100,
//     tags: ['早餐', '豆浆', '包子']
//   }
// ]);

// 将后端Shop数据转换为前端显示格式
const convertApiShopToDisplay = (apiShop: ApiShop): DisplayShop => {
  // 根据店铺名称生成标签（简单的标签生成逻辑）
  const generateTags = (name: string, description?: string): string[] => {
    const tags: string[] = [];
    const nameAndDesc = `${name} ${description || ''}`.toLowerCase();
    
    if (nameAndDesc.includes('麦当劳') || nameAndDesc.includes('汉堡')) tags.push('快餐', '汉堡');
    if (nameAndDesc.includes('肯德基') || nameAndDesc.includes('炸鸡')) tags.push('快餐', '炸鸡');
    if (nameAndDesc.includes('必胜客') || nameAndDesc.includes('披萨')) tags.push('披萨', '意式');
    if (nameAndDesc.includes('海底捞') || nameAndDesc.includes('火锅')) tags.push('火锅', '川菜');
    if (nameAndDesc.includes('寿司') || nameAndDesc.includes('日料')) tags.push('寿司', '日料');
    if (nameAndDesc.includes('甜品') || nameAndDesc.includes('蛋糕')) tags.push('甜品', '蛋糕');
    if (nameAndDesc.includes('饮品') || nameAndDesc.includes('奶茶')) tags.push('饮品', '奶茶');
    
    return tags.length > 0 ? tags : ['美食'];
  };

  // 计算预估送达时间（基于配送费简单估算）
  const estimateDeliveryTime = (deliveryFee: number): number => {
    if (deliveryFee <= 3) return 20;
    if (deliveryFee <= 6) return 30;
    return 40;
  };

  return {
    id: apiShop.id || 0,
    name: apiShop.name || '未命名店铺',
    image: apiShop.image || '/default-shop.jpg',
    rating: apiShop.avRating || 4.5,
    avgPrice: Math.round((apiShop.avAmount || 3000) / 100), // 转换为元
    deliveryFee: Math.round((apiShop.deliveryFee || 500) / 100), // 转换为元
    deliveryTime: estimateDeliveryTime(Math.round((apiShop.deliveryFee || 500) / 100)),
    monthlySales: apiShop.monthlyOrderCount || 0,
    tags: generateTags(apiShop.name || '', apiShop.description || undefined),
    description: apiShop.description || undefined,
    address: apiShop.address || undefined,
    phone: apiShop.phone || undefined,
    startTime: apiShop.startTime || undefined,
    endTime: apiShop.endTime || undefined,
    // 简单的促销标签生成
    promo: apiShop.monthlyOrderCount && apiShop.monthlyOrderCount > 1000 ? '热销店铺' : undefined
  };
};

// 加载店铺数据
const loadShops = async () => {
  loading.value = true;
  try {
    console.log('🚀 开始加载店铺数据...');
    
    // 获取所有店铺数据
    const response = await getShops(1, 50); // 获取前50个店铺
    
    if (response.data && response.data.list) {
      console.log('✅ 店铺数据加载成功:', response.data.list.length, '个店铺');
      
      // 转换数据格式
      const convertedShops = response.data.list.map(convertApiShopToDisplay);
      allShops.value = convertedShops;
      shops.value = convertedShops;
      
      console.log('📊 转换后的店铺数据:', convertedShops);
    } else {
      console.log('⚠️ 没有店铺数据');
      // 如果没有数据，可以使用静态数据作为备用
      // shops.value = staticShops.value;
      message.info('暂无店铺数据');
    }
  } catch (error: any) {
    console.error('❌ 加载店铺数据失败:', error);
    
    if (error.message) {
      message.error(`加载店铺数据失败: ${error.message}`);
    } else {
      message.error('加载店铺数据失败，请检查网络连接');
    }
    
    // 错误时可以使用静态数据作为备用
    // shops.value = staticShops.value;
  } finally {
    loading.value = false;
  }
};

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    shops.value = allShops.value;
    return;
  }
  
  loading.value = true;
  try {
    console.log('🔍 搜索店铺:', searchKeyword.value);
    
    // 使用条件查询接口进行搜索
    const searchConditions = {
      name: searchKeyword.value
    };
    
    const response = await searchShopsEq(searchConditions);
    
    if (response.data && response.data.length > 0) {
      const convertedShops = response.data.map(convertApiShopToDisplay);
      shops.value = convertedShops;
      console.log('✅ 搜索结果:', convertedShops.length, '个店铺');
    } else {
      // 如果API搜索没有结果，在本地数据中搜索
      const localResults = allShops.value.filter(shop => 
        shop.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        shop.tags.some(tag => tag.toLowerCase().includes(searchKeyword.value.toLowerCase()))
      );
      shops.value = localResults;
      
      if (localResults.length === 0) {
        message.info('没有找到相关店铺');
      }
    }
  } catch (error: any) {
    console.error('❌ 搜索失败:', error);
    
    // 搜索失败时在本地数据中搜索
    const localResults = allShops.value.filter(shop => 
      shop.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      shop.tags.some(tag => tag.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    );
    shops.value = localResults;
    
    if (localResults.length === 0) {
      message.warning('搜索失败，请重试');
    }
  } finally {
    loading.value = false;
  }
};

// 分类过滤
const handleFilterChange = (filter: string) => {
  activeFilter.value = filter;
  
  if (filter === '全部') {
    shops.value = allShops.value;
  } else {
    shops.value = allShops.value.filter(shop => 
      shop.tags.some(tag => tag.includes(filter))
    );
  }
  
  console.log('🏷️ 过滤结果:', filter, shops.value.length, '个店铺');
};

// 跳转到店铺详情
const goToShop = (id: number) => {
  console.log('🏪 跳转到店铺:', id);
  router.push(`/shop/${id}`);
};

// 页面加载时获取数据
onMounted(() => {
  loadShops();
});

// 计算属性：过滤后的店铺列表
const filteredShops = computed(() => {
  let result = shops.value;
  
  // 应用搜索过滤
  if (searchKeyword.value.trim()) {
    result = result.filter(shop => 
      shop.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      shop.tags.some(tag => tag.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    );
  }
  
  return result;
});
</script>

<style scoped>
.square-view {
  width: 100%;
  height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #fff5f5 0%, #f8f9ff 100%);
  overflow-y: auto;
  box-sizing: border-box;
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.header h1 {
  color: #ff6b6b;
  font-size: 2.5rem;
  margin-bottom: 16px;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.1);
}

.search-bar {
  display: flex;
  width: 80%;
  max-width: 600px;
}

.search-bar input {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 30px 0 0 30px;
  font-size: 1rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.search-bar button {
  padding: 12px 24px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 0 30px 30px 0;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s;
}

.search-bar button:hover {
  background: #ff5252;
}

.filters {
  display: flex;
  overflow-x: auto;
  padding: 10px 0;
  margin-bottom: 20px;
  gap: 12px;
}

.filter {
  padding: 8px 20px;
  background: white;
  border-radius: 20px;
  font-size: 0.9rem;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.filter.active {
  background: #ff6b6b;
  color: white;
  box-shadow: 0 4px 10px rgba(255,107,107,0.3);
}

.filter:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.shop-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.shop-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 15px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.shop-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0,0,0,0.15);
}

.shop-image {
  height: 180px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.promo-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.shop-info {
  padding: 16px;
}

.shop-info h3 {
  margin: 0 0 8px;
  color: #333;
  font-size: 1.3rem;
}

.rating {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: #666;
}

.stars {
  color: #ffc107;
  letter-spacing: 2px;
}

.details {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  font-size: 0.9rem;
  color: #777;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tags span {
  background: #f0f5ff;
  color: #4dabf7;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #ff6b6b;
  border-top: 4px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 12px 24px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s;
}

.retry-btn:hover {
  background: #ff5252;
}
</style>